import {format} from 'date-fns'
import Redis, {RedisOptions} from 'ioredis'

export default class RedisClient {
  private redis: Redis

  constructor(connection: RedisOptions) {
    this.redis = new Redis(connection)

    this.redis.on('error', error => {
      console.log(
        `\x1B[90m\x1B[1m\u279C\x1B[39m [${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}] \x1B[90m\x1B[1m[Redis]\x1B[0m \x1B[31mError: ${error.message}\x1B[0m`,
      )
    })

    this.redis.on('close', () => {
      console.log(
        `\x1B[90m\x1B[1m\u279C\x1B[39m [${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}] \x1B[90m\x1B[1m[Redis]\x1B[0m \x1B[31mConnection closed.\x1B[0m`,
      )
    })
  }

  async set(key: string, value: string, exp?: number) {
    if (exp) return this.redis.set(key, value, 'PX', exp)
    return this.redis.set(key, value)
  }

  async get(key: string) {
    return this.redis.get(key)
  }

  async del(key: string) {
    return this.redis.del(key)
  }

  async forgetAll() {
    return this.redis.flushall()
  }
}
